package LearnAlgorithm.h_标准数学公式;

/*
等差数列{an}的通项公式为：an = a1 + (n - 1) * d
前n项和公式为：Sn = n * a1 + (n * (n - 1) * d) / 2
		    或    Sn = (n * (a1 + an)) / 2
注意： 以上n均属于正整数。

熟记当d=1,a1=1时
Sn = (n * (n + 1)) / 2
 */
public class a等差数列求和 {
	public static void main(String[] args) {
		int[] arr1 = new int[] {1,2,3,4,5};//15
		int[] arr2 = new int[] {2,4,6,8,10};//30
		System.out.println("Sn = " + sumDengCha(arr2));
		System.out.println("Sn = " + sumDengChaForan(arr2));
		System.out.println("Sn = " + sumSpecial(arr1));
	}
	
	/**
	 * 适用所有等差数列
	 * @return
	 */
	public static int sumDengCha(int[] arr) {
		int n = arr.length;
		int a1 = arr[0];
		int an = arr[n - 1];
		int d = arr[1] - arr[0];
		return n * a1 + (n * (n - 1) * d) / 2;
	}
	
	/**
	 * 适用所有等差数列
	 * @return
	 */
	public static int sumDengChaForan(int[] arr) {
		int n = arr.length;
		int a1 = arr[0];
		int an = arr[n - 1];
		int d = arr[1] - arr[0];
		return (n * (a1 + an)) / 2;
	}
	
	/**
	 * d=1
	 * a1=1
	 * @param arr
	 * @return
	 */
	public static int sumSpecial(int[] arr) {
		int n = arr.length;
		return (n * (n + 1)) / 2;
	}
}
